package com.example.gkb_signalr

import androidx.annotation.NonNull

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** GkbSignalrPlugin */
class GkbSignalrPlugin : FlutterPlugin, MethodCallHandler {

    var channel: MethodChannel? = null

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "gkb_signalr")
        channel?.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            CallMethod.ConnectToServer.value -> {
                val arguments = call.arguments as Map<*, *>
                channel?.let {
                    SignalR.connectToServer(
                        arguments["url"] as String,
                        arguments["token"] as String,
                        result, it)
                }
            }
            CallMethod.Reconnect.value -> {
                channel?.let { SignalR.reconnect(result, it) }
            }
            CallMethod.Stop.value -> {
                SignalR.stop(result)
            }
            CallMethod.IsConnected.value -> {
                SignalR.isConnected(result)
            }
            CallMethod.AckMessage.value -> {
                val arguments = call.arguments as Map<*, *>
                SignalR.ackMessage(arguments["ids"] as List<Int>)
            }
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel?.setMethodCallHandler(null)
    }
}
